package user

import (
	"gorm.io/gorm"
	"wskyygyso/api/app/models"
	"wskyygyso/api/pkg/database"
	"wskyygyso/api/pkg/hash"
)

type User struct {
	models.BaseModel
	Name         string `json:"name,omitempty"`
	Email        string `json:"-"` //json:"-" JSON 解析器忽略字段
	Phone        string `json:"-"`
	PassWord     string `json:"-"`
	City         string `json:"city,omitempty"`
	Introduction string `json:"introduction,omitempty"`
	Avatar       string `json:"avatar,omitempty"`
	models.CommonTimestampsField
}

func (u *User) Create() {
	database.DB.Create(&u)
}

// BeforeSave GORM 的模型钩子，在创建和更新模型前调用
func (u *User) BeforeSave(tx *gorm.DB) (err error) {
	if !hash.BcryptIsHashed(u.PassWord) {
		u.PassWord = hash.BcryptHash(u.PassWord)
	}
	return
}

// ComparePassword 密码是否正确
func (u *User) ComparePassword(_password string) bool {
	return hash.BcryptCheck(_password, u.PassWord)
}

func (u *User) Save() (rowsAffected int64) {
	result := database.DB.Save(&u)
	return result.RowsAffected
}

func (u User) Delete() (rowsAffected int64) {
	result := database.DB.Delete(&u)
	return result.RowsAffected
}

func GetByMulti(name string) (userModel User) {
	database.DB.Where("email=?", name).Or("phone=?", name).Or("name=?", name).First(&userModel)
	return
}

func GetByPhone(phone string) (userModel User) {
	database.DB.Where("phone=?", phone).First(&userModel)
	return
}

func Get(idStr string) (userModel User) {
	database.DB.Where("id=?", idStr).First(&userModel)
	return
}

func All() (userModels []User) {
	database.DB.Find(&userModels)
	return
}
